﻿using IP2Region.Net.XDB;
using Microsoft.EntityFrameworkCore;
using Polaris.Common;
using Polaris.Domain.Interfaces.Admin;
using Polaris.Domain.Model.DbEntity;
using Polaris.Domain.Model.Dto.Sys_Dictionary.Response;
using Polaris.Domain.Model.Dto.Tag.Request;
using Polaris.Domain.Model.Dto.Tag.Response;
using Polaris.Domain.Model.Entity.Base;
using Polaris.Domain.Model.Entity.Exception;
using Polaris.Domain.Repository.Interfaces;
using Polaris.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Polaris.Infrastructure.DomainService.Admin
{
    public class TagService : ITag
    {
        private readonly IBaseRepository<Tag> _tag;
        private readonly PolarisDbContext _dbContext;

        public TagService(IBaseRepository<Tag> tag, PolarisDbContext dbContext)
        {
            _tag = tag;
            _dbContext = dbContext;
        }

        /// <summary>
        /// 创建标签
        /// </summary>
        /// <param name="createTagInfo"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task CreateTag(CreateTagInfoRequest createTagInfo, Guid? userId)
        {
            try
            {
                var tag = new Tag()
                {
                    CreateBy = userId,
                    CreatedTime = DateTime.Now,
                    Description = createTagInfo.Description,
                    Enable = createTagInfo.Enable,
                    Id = Guid.NewGuid(),
                    IsDelete = false,
                    Name = createTagInfo.TagName,
                    Type = createTagInfo.TagType,
                };

                await _tag.AddEntityAsync(tag);
                await _tag.CommitAsync();
            }
            catch (Exception ex)
            {
                throw new CustomException(Domain.Model.Enum.ResultCode.FAIL, ex.Message);
            }
        }

        /// <summary>
        /// 删除标签
        /// </summary>
        /// <param name="id"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task DeleteTag(string id, Guid? userId)
        {
            var data = await _tag.QueryAll(d => d.Id.ToString() == id).FirstOrDefaultAsync();
            if (data == null)
            {
                throw new CustomException(Domain.Model.Enum.ResultCode.NO_DATA, "找不到数据");
            }
            else
            {
                data.IsDelete = true;
                data.UpdatedBy = userId;
                data.UpdatedTime = DateTime.Now;
                _tag.UpdateEntity(data);
                await _tag.CommitAsync();
            }
        }

        /// <summary>
        /// 根据id获取标签数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<TagInfoResponse> GetTagById(string id)
        {
            var data = await _tag.QueryAll(d => d.Id.ToString() == id).FirstOrDefaultAsync();
            if (data == null)
            {
                throw new CustomException(Domain.Model.Enum.ResultCode.NO_DATA, "找不到数据");
            }
            else
            {
                var result = new TagInfoResponse()
                {
                    Description = data.Description,
                    Enable = data.Enable,
                    Id = data.Id.ToString(),
                    TagName = data.Name,
                    TagType = data.Type
                };
                return result;
            }
        }

        /// <summary>
        /// 根据字典code来获取标签类型数据
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<List<TagOptionResponse>> GetTagByType(string type)
        {
            var linqStr = from t in _dbContext.Tag
                          join d in _dbContext.Sys_Dictionary_Item
                          on t.Type equals d.Id.ToString()
                          where d.Value == type
                          select new
                          {
                              t.Id,
                              Value = t.Name
                          };

            var result = new List<TagOptionResponse>();

            (await linqStr.ToListAsync()).ForEach(data =>
             {
                 result.Add(new TagOptionResponse()
                 {
                     Id = data.Id.ToString(),
                     Value = data.Value
                 });
             });
            return result;
        }

        /// <summary>
        /// 获取标签列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<PaginationInfo<TagInfoResponse>> GetTagList(QueryTagRequest query)
        {
            Expression<Func<Tag, bool>> exp = e => e.IsDelete == false;
            exp = exp.And(e => !e.IsDelete);

            // 动态组合where条件到LINQ查询
            var linqStr = _dbContext.Tag
                .Where(exp)  // 应用动态where条件
                .Join(
                    _dbContext.Sys_Dictionary_Item,
                    t => t.Type,
                    dict => dict.Id.ToString(),
                    (t, dict) => new { t, dict }
                )
                .Select(result => new TagInfoResponse
                {
                    Id = result.t.Id.ToString(),
                    Description = result.t.Description,
                    Enable = result.t.Enable,
                    TagName = result.t.Name,
                    TagType = result.dict.Value
                }).Skip((query.PageIndex - 1) * query.PageSize).Take(query.PageSize);

            var result = await linqStr.ToListAsync();

            var total = await _tag.GetEntitiesCountAsync(exp);
            return ApiResult.CreatePaginationInfo(
                                                                    PageIndex: query.PageIndex,
                                                                    PageSize: query.PageSize,
                                                                    Total: total,
                                                                    Result: result
                                                                   );
        }

        /// <summary>
        /// 修改标签
        /// </summary>
        /// <param name="update"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task UpdateTag(UpdateTagInfoRequest update, Guid? userId)
        {
            var data = await _tag.QueryAll(d => d.Id.ToString() == update.Id).FirstOrDefaultAsync();
            if (data == null)
            {
                throw new CustomException(Domain.Model.Enum.ResultCode.NO_DATA, "找不到数据");
            }
            else
            {
                data.Name = update.TagName;
                data.Description = update.Description;
                data.Enable = update.Enable;
                data.Type = update.TagType;
                data.UpdatedBy = userId;
                data.UpdatedTime = DateTime.Now;

                _tag.UpdateEntity(data);
                await _tag.CommitAsync();
            }
        }
    }
}
